package com.gzrhhscd.aop;

import com.alibaba.fastjson.JSONObject;
import com.gzrhhscd.Pojo.OperateLog;
import com.gzrhhscd.mapper.OperateLogMapper;
import com.gzrhhscd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;
@Around("@annotation(com.gzrhhscd.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
    //1.执行原程序
    long begin=System.currentTimeMillis();
    Object result=joinPoint.proceed();
   long end=System.currentTimeMillis();
    //costTime
    long costTime=end-begin;
    //get login user id by jwx
    String jwt=request.getHeader("token");
    Claims claims= JwtUtils.parseJwt(jwt);
    Integer operateUser= (Integer) claims.get("id");
    //operateTime
    LocalDateTime operateTime=LocalDateTime.now();
    //operate className
    String className=joinPoint.getTarget().getClass().getName();
    //methodName
    String methodName=joinPoint.getSignature().getName();
    //methodParams
    Object[] args= joinPoint.getArgs();
    String methodParams= Arrays.toString(args);

    //returnValue
    String returnValue=JSONObject.toJSONString(result);


    //2.create  log
    OperateLog operateLog=new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
    //3.insert log
    operateLogMapper.insert(operateLog);
    log.info("AOP中记录操作日志{}",operateLog);
    //return result
    return result;

    }


}
